package com.soul.dj.util.http;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import com.soul.dj.ui.activity.BaseActivity;
import com.soul.dj.ui.fragment.BaseFragment;
import okhttp3.Callback;

import android.text.TextUtils;
import android.util.Log;

import com.soul.dj.util.http.json.Json;
import com.soul.dj.util.http.json.JsonProcessUtil;
import okhttp3.Call;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class JSONCallBack<T> implements Callback {
	private Object context;
	private String tag;
	private Map<String,Object> map = new HashMap<>();

	private Handler handler;
	private Message msg = new Message();
	private Class<T> contentClass;

	public JSONCallBack() {
		this(null, null, null);
	}

	public JSONCallBack(Object context, String tag, Class<T> class1) {
		this.context = context;
		this.tag = tag;
		this.contentClass = class1;
		handler = new MainHandler(context);
		map.put("tag",tag);

	}

	@SuppressWarnings("unchecked")
    @Override
    public void onResponse(Call call, Response response) throws IOException {

		if (context == null) {
			return;
		}
        String t = response.body().string();
		Log.d("HttpProcessor", contentClass+"请求返回参数:" + t);

		Json<T> json = null;

		try {
			json = JsonProcessUtil.jsonToBean(t);

			if (json == null || !json.isSuccess()) {
				map.put("code",json.getResult_code());
				map.put("title","错误");
				map.put("str",json.getMsg());
				msg.what = Activity.RESULT_CANCELED;
				msg.obj = map;
				handler.sendMessage(msg);
				return;
			}
			if (contentClass != null && !TextUtils.isEmpty(t)) {
				json = JsonProcessUtil.jsonToBean(t, contentClass);

			}
			Object o = json.getObj();
			map.put("result",o);
			msg.what = Activity.RESULT_OK;
			msg.obj = map;
			handler.sendMessage(msg);
		} catch (Exception e) {
			Log.e(tag, "JSON解析失败", e);

			map.put("code","-1");
			map.put("title","错误");
			map.put("str","数据解析失败");
			msg.what = Activity.RESULT_CANCELED;
			msg.obj = map;
			handler.sendMessage(msg);

			return;
		}



	}

    @Override
    public void onFailure(Call call, IOException e) {
		if (context == null) {
			return;
		}
		msg.what = Activity.RESULT_FIRST_USER;
		msg.obj = map;
		handler.sendMessage(msg);
	}
}
